package com.atguigu.interactive;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Data{
    private int flag = 1;

    private final Lock lock = new ReentrantLock();
    Condition c1 = lock.newCondition();
    Condition c2 = lock.newCondition();
    Condition c3 = lock.newCondition();

    public void Print5() throws InterruptedException{
        lock.lock();
        try{
            while(flag != 1){
                c1.await();
            }
            for(int i = 0; i < 5; i++){
                System.out.println(Thread.currentThread().getName() + "\t" + (i+1));
            }
            flag = 2;
            c2.signal();
        }finally{
            lock.unlock();
        }
    }

    public void Print10() throws InterruptedException{
        lock.lock();
        try{
            while(flag != 2){
                c2.await();
            }
            for(int i = 0; i < 10; i++){
                System.out.println(Thread.currentThread().getName() + "\t" + (i+1));
            }
            flag = 3;
            c3.signal();
        }finally{
            lock.unlock();
        }
    }

    public void Print15() throws InterruptedException{
        lock.lock();
        try{
            while(flag != 3){
                c3.await();
            }
            for(int i = 0; i < 15; i++){
                System.out.println(Thread.currentThread().getName() + "\t" + (i+1));
            }
            flag = 1;
            c1.signal();
        }finally{
            lock.unlock();
        }
    }
}



public class ThreadOrderAccess {
    public static void main(String[] args) {
        Data data = new Data();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.Print5();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.Print10();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.Print15();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"C").start();
    }
}
